<template>
  <div class="warehouse-detail-container">
    <!-- 仓库信息 -->
    <el-card v-loading="loading" class="warehouse-info-card">
      <template #header>
        <div class="card-header">
          <div>
            <el-button :icon="ArrowLeft" @click="goBack">Back</el-button>
          </div>
          <h2 style="margin: 0">{{ warehouseInfo.name }}</h2>
          <div style="width: 80px"></div>
        </div>
      </template>
      
      <el-descriptions :column="3" border>
        <el-descriptions-item label="Location">
          {{ warehouseInfo.location }}
        </el-descriptions-item>
        <el-descriptions-item label="Capacity">
          {{ warehouseInfo.capacity }} units
        </el-descriptions-item>
        <el-descriptions-item label="Manager">
          {{ warehouseInfo.manager }}
        </el-descriptions-item>
        <el-descriptions-item label="Phone">
          {{ warehouseInfo.phone || 'N/A' }}
        </el-descriptions-item>
        <el-descriptions-item label="Status">
          <el-tag :type="getStatusType(warehouseInfo.status)">
            {{ getStatusText(warehouseInfo.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="Total Items">
          {{ totalItems }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 水果列表 -->
    <el-card style="margin-top: 20px">
      <template #header>
        <div class="card-header">
          <h3 style="margin: 0">🍎 Fruits in this Warehouse</h3>
          <el-button type="primary" :icon="Plus" @click="showAddDialog">
            Add Fruit
          </el-button>
        </div>
      </template>

      <el-table 
        v-loading="tableLoading"
        :data="fruits" 
        style="width: 100%" 
        stripe
      >
        <el-table-column prop="fruit.name" label="Fruit Name" width="150" />
        <el-table-column prop="fruit.category" label="Category" width="150" />
        <el-table-column label="Price" width="120">
          <template #default="scope">
            ${{ Number(scope.row.fruit.price).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="Quantity in Warehouse" width="180">
          <template #default="scope">
            <el-tag type="success">{{ scope.row.quantity }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="fruit.total_stock" label="Total Stock" width="120" />
        <el-table-column prop="fruit.stock" label="Available Stock" width="140">
          <template #default="scope">
            <span :style="{ color: scope.row.fruit.stock < 50 ? '#f56c6c' : '#67c23a' }">
              {{ scope.row.fruit.stock }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="Created At" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="Operations" fixed="right" width="200">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary" 
              :icon="Edit" 
              @click="handleEdit(scope.row)"
            >
              Edit
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              :icon="Delete" 
              @click="handleDelete(scope.row)"
            >
              Delete
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态 -->
      <el-empty 
        v-if="!tableLoading && fruits.length === 0" 
        description="No fruits in this warehouse"
      />
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="500px"
      @close="resetForm"
    >
      <el-form 
        ref="formRef"
        :model="form" 
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="Select Fruit" prop="fruit_id">
          <el-select 
            v-model="form.fruit_id" 
            placeholder="Please select fruit" 
            style="width: 100%"
            :disabled="isEdit"
            @change="handleFruitChange"
          >
            <el-option 
              v-for="fruit in availableFruits" 
              :key="fruit.id" 
              :label="`${fruit.name} (${fruit.category})`" 
              :value="fruit.id"
            >
              <span>{{ fruit.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                {{ fruit.category }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 显示选中水果的信息 -->
        <el-alert 
          v-if="selectedFruit" 
          :closable="false"
          type="info"
          style="margin-bottom: 15px"
        >
          <template #default>
            <div><strong>Price:</strong> ${{ Number(selectedFruit.price).toFixed(2) }}</div>
            <div><strong>Category:</strong> {{ selectedFruit.category }}</div>
            <div><strong>Total Stock:</strong> {{ selectedFruit.total_stock }}</div>
            <div><strong>Available Stock:</strong> {{ availableStock }}</div>
          </template>
        </el-alert>

        <el-form-item label="Quantity" prop="quantity">
          <el-input-number 
            v-model="form.quantity" 
            :min="0"
            style="width: 100%"
            :controls-position="'right'"
          />
          <div style="margin-top: 8px">
            <div style="color: #67c23a; font-size: 13px; font-weight: 500">
              📦 Maximum Available: {{ availableStock }} units
            </div>
            <div v-if="isEdit" style="color: #909399; font-size: 12px; margin-top: 3px">
              (Current in warehouse: {{ fruits.find(f => f.fruit_id === form.fruit_id)?.quantity || 0 }} + Available stock: {{ selectedFruit?.stock || 0 }})
            </div>
            <div v-else style="color: #909399; font-size: 12px; margin-top: 3px">
              (From available stock)
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="handleSave" :loading="saveLoading">
          Confirm
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ArrowLeft, Plus, Edit, Delete } from '@element-plus/icons-vue';
import { warehouseAPI, fruitAPI } from '@/api';

const route = useRoute();
const router = useRouter();

const warehouseId = ref(route.params.id);
const warehouseInfo = ref({});
const fruits = ref([]);
const allFruits = ref([]);
const loading = ref(false);
const tableLoading = ref(false);
const saveLoading = ref(false);

const dialogVisible = ref(false);
const dialogTitle = ref('Add Fruit');
const formRef = ref(null);
const isEdit = ref(false);
const editId = ref(null);

const form = ref({
  fruit_id: null,
  quantity: 0
});

const formRules = {
  fruit_id: [
    { required: true, message: 'Please select fruit', trigger: 'change' }
  ],
  quantity: [
    { required: true, message: 'Please enter quantity', trigger: 'blur' },
    { type: 'number', min: 0, message: 'Quantity cannot be negative', trigger: 'blur' }
  ]
};

// 选中的水果信息
const selectedFruit = computed(() => {
  if (!form.value.fruit_id) return null;
  return allFruits.value.find(f => f.id === form.value.fruit_id);
});

// 可用库存（水果的总库存 + 如果是编辑模式则加上当前仓库原有的数量）
const availableStock = computed(() => {
  if (!selectedFruit.value) return 0;
  
  // 水果的总库存已经是扣减了分配给各仓库的数量后的剩余库存
  let available = selectedFruit.value.stock;
  
  // 如果是编辑模式，加上当前仓库原有的数量（因为可以重新分配）
  if (isEdit.value) {
    const currentQuantity = fruits.value.find(f => f.fruit_id === form.value.fruit_id)?.quantity || 0;
    available += currentQuantity;
  }
  
  return available;
});

// 总库存量
const totalItems = computed(() => {
  return fruits.value.reduce((sum, item) => sum + item.quantity, 0);
});

// 可添加的水果列表（排除已在仓库中的）
const availableFruits = computed(() => {
  if (isEdit.value) {
    // 编辑时显示所有水果
    return allFruits.value;
  }
  
  // 添加时只显示未在该仓库中的水果
  const existingFruitIds = fruits.value.map(f => f.fruit_id);
  return allFruits.value.filter(f => !existingFruitIds.includes(f.id));
});

// 加载仓库信息
const loadWarehouseInfo = async () => {
  loading.value = true;
  try {
    const response = await warehouseAPI.getById(warehouseId.value);
    
    if (response.success) {
      warehouseInfo.value = response.data;
    }
  } catch (error) {
    console.error('Failed to load warehouse info:', error);
    ElMessage.error('Failed to load warehouse information');
  } finally {
    loading.value = false;
  }
};

// 加载仓库中的水果列表
const loadFruits = async () => {
  tableLoading.value = true;
  try {
    const response = await warehouseAPI.getWarehouseFruits(warehouseId.value);
    
    if (response.success) {
      fruits.value = response.data;
    }
  } catch (error) {
    console.error('Failed to load fruits:', error);
    ElMessage.error('Failed to load fruits');
  } finally {
    tableLoading.value = false;
  }
};

// 加载所有水果（用于添加）
const loadAllFruits = async () => {
  try {
    const response = await fruitAPI.getList();
    
    if (response.success) {
      allFruits.value = response.data;
    }
  } catch (error) {
    console.error('Failed to load all fruits:', error);
  }
};

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    'active': 'success',
    'inactive': 'info',
    'maintenance': 'warning'
  };
  return statusMap[status] || 'info';
};

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    'active': 'Active',
    'inactive': 'Inactive',
    'maintenance': 'Maintenance'
  };
  return textMap[status] || status;
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return date.toLocaleString();
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 显示添加对话框
const showAddDialog = () => {
  dialogTitle.value = 'Add Fruit to Warehouse';
  isEdit.value = false;
  editId.value = null;
  resetForm();
  dialogVisible.value = true;
};

// 水果选择变更
const handleFruitChange = () => {
  // 重置数量
  form.value.quantity = 0;
};

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = 'Edit Fruit Quantity';
  isEdit.value = true;
  editId.value = row.id;
  form.value = {
    fruit_id: row.fruit_id,
    quantity: row.quantity
  };
  dialogVisible.value = true;
};

// 保存
const handleSave = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return;
    
    saveLoading.value = true;
    try {
      let response;
      
      if (isEdit.value) {
        // 更新
        response = await warehouseAPI.updateWarehouseFruit(
          warehouseId.value,
          editId.value,
          form.value
        );
      } else {
        // 创建
        response = await warehouseAPI.addFruitToWarehouse(
          warehouseId.value,
          form.value
        );
      }
      
      if (response.success) {
        ElMessage.success(response.message || 'Saved successfully');
        dialogVisible.value = false;
        loadFruits();
        loadAllFruits(); // 重新加载水果列表以更新库存
      }
    } catch (error) {
      console.error('Save failed:', error);
      // 显示后端返回的错误信息
      const errorMessage = error.response?.data?.message || error.message || 'Operation failed';
      ElMessage.error(errorMessage);
    } finally {
      saveLoading.value = false;
    }
  });
};

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `Are you sure you want to remove "${row.fruit.name}" from this warehouse?`, 
    'Confirm', 
    {
      confirmButtonText: 'Confirm',
      cancelButtonText: 'Cancel',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await warehouseAPI.removeFruitFromWarehouse(
        warehouseId.value,
        row.id
      );
      
      if (response.success) {
        ElMessage.success(`"${row.fruit.name}" removed successfully`);
        loadFruits();
        loadAllFruits();
      }
    } catch (error) {
      console.error('Delete failed:', error);
      // 显示后端返回的错误信息
      const errorMessage = error.response?.data?.message || error.message || 'Delete failed';
      ElMessage.error(errorMessage);
    }
  }).catch(() => {});
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  form.value = {
    fruit_id: null,
    quantity: 0
  };
};

// 页面加载时获取数据
onMounted(() => {
  loadWarehouseInfo();
  loadFruits();
  loadAllFruits();
});
</script>

<style scoped>
.warehouse-detail-container {
  padding: 20px;
}

.warehouse-info-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>

